package tom.vertx.core.demo13;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.http.HttpServer;
import io.vertx.core.spi.VertxMetricsFactory;
import io.vertx.ext.dropwizard.DropwizardMetricsOptions;
import io.vertx.ext.dropwizard.Match;
import io.vertx.ext.dropwizard.MatchType;
import io.vertx.ext.dropwizard.MetricsService;
import io.vertx.ext.dropwizard.impl.VertxMetricsFactoryImpl;

/**
 * 默认未开启metric统计，可以通过spi形式实现，也可以编程实现{@link VertxMetricsFactory}方式.
 * @see io.vertx.core.impl.VertxImpl#initialiseMetrics(VertxOptions)
 * @author ZHUFEIFEI
 */
public class MetricSpiDemo {

  public static void main(String[] args) {
    //引入 vertx-dropwizard-metrics, 编程方式注入VertxMetricsFactory, 不指定时，通过spi扫描加载
    Vertx.vertx(new VertxOptions().setMetricsOptions(
      new DropwizardMetricsOptions()
        .setEnabled(true)
        .setJmxEnabled(true)
        .setJmxDomain("localhost")
        //通过MetricsService.getMetricsSnapshot(baseName)获取维度信息
//        .setBaseName("mtest")
        .addMonitoredHttpServerUri(new Match().setValue("/"))
        .addMonitoredHttpServerUri(new Match().setValue("/hello/.*").setType(MatchType.REGEX))
        .addMonitoredHttpClientEndpoint(new Match().setValue("localhost:.*").setType(MatchType.REGEX))
        .addMonitoredEventBusHandler(new Match().setValue(".*").setType(MatchType.REGEX))
        .setFactory(new VertxMetricsFactoryImpl())
    ))
      .deployVerticle(new V());
  }

  static class V extends AbstractVerticle {
    @Override
    public void start(Promise<Void> startPromise) throws Exception {
      HttpServer server = vertx.createHttpServer().requestHandler(req -> {
        req.response().end("Hello!");
      }).listen(8888, rs -> {
        if (rs.succeeded()) {
          System.out.println("HttpServer started.");
        } else {
          rs.cause().printStackTrace();
        }
      });

      MetricsService metricsService = MetricsService.create(vertx);
      vertx.setPeriodic(2000L, id -> {
        //监控维度特别多
        //metricsService.metricsNames().forEach(System.out::println);
        //获取维度信息
        System.out.println("HttpServer Metrics => " + metricsService.getMetricsSnapshot(server));
        System.out.println("EventBus Metrics => " + metricsService.getMetricsSnapshot(vertx.eventBus()));
      });
    }
  }

}
